<template>
	<div class="table-box">
		<proTable
			ref="proTableRef"
			:columns="columns"
			:toolButton="false"
			:requestApi="api.GetAuthorizationDetailedInfoList"
			:initParam="initParam"
			:dataCallback="dataCallback"
		>
			<template #tableHeader="scope">
				<div class="header-info" v-if="isPlatform">
					<el-descriptions :title="cominfo.companyName">
						<el-descriptions-item label="客服电话：">{{ cominfo.customerServiceTel }}</el-descriptions-item>
						<el-descriptions-item label="使用期限：">{{ cominfo.usageTime }}</el-descriptions-item>
						<el-descriptions-item label="使用周期：">{{ cominfo.daysRemaining }}</el-descriptions-item>
						<el-descriptions-item label="剩余使用天数：">{{ cominfo.daysRemaining }} </el-descriptions-item>
						<el-descriptions-item label="授权码总数：">{{ cominfo.clientAuthorizationCodeNumber }}</el-descriptions-item>
						<el-descriptions-item label="剩余授权码：">{{ cominfo.surplusAuthorization }}</el-descriptions-item>
					</el-descriptions>
				</div>
				<div v-if="!isPlatform" class="but">
					<el-button plain type="primary" :icon="Files" @click="batchOperation(scope.selectedListIds)">批量审核</el-button>
				</div>
			</template>
			<template #operation="scope">
				<el-space>
					<el-tag @click="authorization(1, scope.row)">授权安装</el-tag>
					<el-tag @click="authorization(2, scope.row)">不予授权</el-tag>
				</el-space>
			</template>
			<template #authorizationCode="scope">
				<el-link v-if="scope.row.states == 1" v-copy="scope.row.authorizationCode" type="primary">{{
					scope.row.authorizationCode
				}}</el-link>
				<span v-else>--</span>
			</template>
			<template v-if="!isPlatform" #companyName="scope">
				{{ scope.row.companyName }}
			</template>
			<template v-if="isPlatform" #xx="scope">
				<el-tag v-if="!scope.row.xx && scope.row.states == 1" @click="getcode(scope.row)">查看安装密钥</el-tag>
				<el-link v-else v-copy="scope.row.xx" type="primary">{{ scope.row.xx }}</el-link>
			</template>
			<template #userTel="scope">
				{{ phoneFormat(scope.row.userTel) }}
			</template>
		</proTable>
		<el-dialog v-model="dialogTableVisible" title="查看授权码">
			<el-steps :active="setps" align-center>
				<el-step title="1. 身份确认" />
				<el-step title="2. 密码验证" />
				<el-step title="3. 查看授权密钥" />
			</el-steps>
			<div class="codeFrom" v-if="setps == 1">
				<div class="title">{{ `请输入手机号${phoneFormat(globalStore.userInfo.userTel)}收到的验证码` }}</div>
				<el-input style="width: 50%" v-model="codeNumber">
					<template #prepend> 验证码 </template>
				</el-input>
			</div>
			<div class="from-2" v-if="setps == 2">
				<div class="from-item">
					<div class="label">商户名称：</div>
					<div class="value">{{ rowData.companyName }}</div>
				</div>
				<div class="from-item">
					<div class="label">登录密码：</div>
					<div class="value">
						<el-input type="password" placeholder="请输入密码" style="width: 50%" v-model="from_2.password"></el-input>
					</div>
				</div>
				<div class="from-item">
					<div class="label">验证码：</div>
					<div class="value">
						<el-input v-model="from_2.identifyCode" style="width: 35%; margin-right: 15px" />
						<imageCode :change="data.change_img_code" @click="changeImageCode" @get-code="backImageCode" />
					</div>
				</div>
			</div>
			<div class="codeFrom" v-if="setps == 3">
				<div class="title">温馨提示：授权码可见时长60分钟，请及时安装！</div>
				<el-link v-copy="auditCode" type="primary">{{ auditCode }}</el-link>
			</div>
			<div class="steps-button">
				<el-button style="margin-top: 12px" @click="handleNextClick">{{ setps == 3 ? "知道了" : "下一步" }}</el-button>
			</div>
		</el-dialog>
	</div>
</template>
<script lang="tsx" setup name="logs">
import { ref, reactive, computed, watch } from "vue";
import { Files } from "@element-plus/icons-vue";
import api from "@/api/modules/companyInfo";
import { ColumnProps } from "@/components/ProTable/interface";
import proTable from "@/components/ProTable/index.vue";
import { ElMessageBox, ElMessage } from "element-plus";
import { useHandleData } from "@/hooks/useHandleData";
import { phoneFormat } from "@/utils/util";
import imageCode from "@/components/CodeImage/index.vue";
import md5 from "js-md5";
import { GlobalStore } from "@/stores";
// 获取 ProTable 元素，调用其获取刷新数据方法（还能获取到当前查询参数，方便导出携带参数）
const proTableRef = ref();
const globalStore = GlobalStore();
const isPlatform = globalStore.isPlatform;
// 查看密钥弹出框
const dialogTableVisible = ref<boolean>(false);
// 步骤条进度值
const setps = ref<number>(1);
// 暂存查看密钥的列数据
const rowData = ref<any>({
	id: "",
	userId: "",
	userName: "",
	userTel: "",
	companyId: "",
	companyName: "",
	authorizationCode: "",
	authorizationSerialNumber: "",
	surplusAuthorization: 2,
	createTime: "",
	updateUserId: "",
	updateUserName: "",
	updateTime: "",
	states: 1
});
const auditCode = ref<string>("64737sj739dh");
// 发送短信后返回的code
const SendMessageCode = ref<string>("");
// 短信验证码数据
const codeNumber = ref<string | number>();
// 步骤条2的表单数据
const from_2 = ref<any>({
	password: "",
	identifyCode: ""
});
// 如果表格需要初始化请求参数，直接定义传给 ProTable(之后每次请求都会自动带上该参数，此参数更改之后也会一直带上，改变此参数会自动刷新表格数据)
const initParam = reactive({
	isSelectSuccess: false,
	PaymentStatus: null
});
// dataCallback 是对于返回的表格数据做处理，如果你后台返回的数据不是 datalist && total && pageNum && pageSize 这些字段，那么你可以在这里进行处理成这些字段
const dataCallback = (data: any) => {
	console.log(data.totalCount);
	return {
		list: data.data,
		total: data.totalCount
	};
};
//获取客户名称集合
const getCompanyNameList = async () => {
	let { result } = await api.GetCompanyNameList();
	let { data } = result as any;
	data.unshift({ id: "", companyName: "全部" });
	return result;
};

const cominfo = ref<any>({});
//获取商户授权基本信息
const getcompanyinfo = async () => {
	if (!isPlatform) return;
	let ret = await api.GetAuthorizationCompanyInfo({ companyId: globalStore.userInfo.companyInfo.id });
	let { data } = ret.result;
	cominfo.value = data;
};
getcompanyinfo();
// 表格数据变化，清空批量选项
watch(
	() => proTableRef.value?.tableData,
	() => {
		proTableRef.value.clearSelection();
	}
);
const headerRender = (row: ColumnProps) => {
	return (
		<el-tooltip class="box-item" effect="dark" content={row.label} placement="top-start">
			{row.label}
		</el-tooltip>
	);
};
// 表格配置项
const columns = computed((): Partial<ColumnProps>[] => {
	let data: Partial<ColumnProps>[] = [
		{ type: "selection", width: 80, fixed: "left" },
		{ prop: "userName", label: "联系人" },
		{ prop: "userTel", label: "手机号码" },
		// {
		// 	prop: "companyName",
		// 	label: "商户名称"
		// },
		{
			prop: "companyId",
			label: "商户名称",
			enum: getCompanyNameList,
			search: { el: "select", props: { filterable: true }, defaultValue: "" },
			fieldNames: { label: "companyName", value: "id" }
		},
		{
			prop: "authorizationCode",
			label: "授权码"
		},
		{ prop: "authorizationSerialNumber", label: "电脑序列号" },
		{ prop: "surplusAuthorization", headerRender, label: "当前授权剩余(台)" },
		{ prop: "createTime", label: "提交日期" },
		{
			prop: "states",
			label: "审核状态",
			enum: [
				{ label: "全部", value: "" },
				{ label: "待授权", value: 0 },
				{ label: "已授权", value: 1 },
				{ label: "不予授权", value: 2 }
			],
			search: { el: "select", props: { filterable: true }, defaultValue: "" }
		},
		// { prop: "xx", label: "安装密钥" },
		{ prop: "updateUserName", label: "审核人" },
		{ prop: "updateTime", label: "审核时间" },
		{
			prop: "name",
			label: "关键字",
			isShow: false,
			search: { el: "input", props: { placeholder: "请输入联系人/商户名称" } }
		},
		{ prop: "operation", label: "操作", width: 200, fixed: "right" }
	];
	if (isPlatform) {
		data = data.filter(i => {
			return (
				i.prop == "userName" ||
				i.prop == "userTel" ||
				i.prop == "authorizationSerialNumber" ||
				i.prop == "createTime" ||
				i.prop == "authorizationCode" ||
				// i.prop == "xx" ||
				i.prop == "updateTime"
			);
		});
		return data;
	}
	data = data.filter(i => i.prop != "xx");
	return data;
});
// 批量审核
const batchOperation = (ids: any[]) => {
	if (!ids.length) {
		ElMessage.error("请选择需要操作的列表");
		return;
	}
	ElMessageBox.confirm("请选择是否授权", "", {
		distinguishCancelAndClose: true,
		confirmButtonText: "授权安装",
		cancelButtonText: "不予授权",
		center: true
	})
		.then(async () => {
			//授权
			let { result } = await api.AuthorizationSteats({ States: 1, list: ids });
			let { code, message } = result;
			if (code != 200) {
				ElMessageBox.alert("调用接口失败：" + message);
				return;
			}
			ElMessage.success("批量授权完成");
			proTableRef.value.clearSelection();
			proTableRef.value.getTableList();
		})
		.catch(async (action: any) => {
			if (action == "cancel") {
				let { result } = await api.AuthorizationSteats({ States: 2, list: ids });
				let { code, message } = result;
				if (code != 200) {
					ElMessageBox.alert("调用接口失败：" + message);
					return;
				}
				ElMessage.success("批量不予授权完成");
				proTableRef.value.clearSelection();
				proTableRef.value.getTableList();
			}
		});
};
// 授权审核
const authorization = async (states: any, row: any) => {
	await useHandleData(api.AuthorizationSteats, { states, list: [row.id] }, `${states == 1 ? "确定授权安装" : "拒绝授权安装"}`);
	proTableRef.value.getTableList();
};
// 查看密钥
const getcode = async (row: any) => {
	rowData.value = row;
	let { result } = await api.SendMessageApi({ tel: row.userTel });
	ElMessage.success("短信已发送");
	SendMessageCode.value = result.data?.verificationCode || "";
	dialogTableVisible.value = true;
};
// 步骤条下一步按钮
const handleNextClick = async () => {
	if (setps.value == 1) {
		console.log(proTableRef.value.tableData);
		if (!codeNumber.value) {
			ElMessage.error("请输入验证码");
			return;
		}
		//前端验证用户输入验证码和短信验证码是否一致
		// if (codeNumber.value != SendMessageCode.value) {
		// 	ElMessage.error("验证码错误");
		// 	return;
		// }
		setps.value++;
		return;
	}
	if (setps.value == 2) {
		let { result } = await api.AuthorizationVerificationPasswordApi({ password: md5(from_2.value.password).toUpperCase() });
		if (result.code !== 200) {
			ElMessage.error("密码错误！");
			return;
		}
		let bool: boolean = md5(from_2.value.identifyCode) == data.img_code;
		if (!bool) {
			ElMessage.error("验证码错误！");
			return;
		}
		let res = await api.GetAuthorizationCodeApi({ id: rowData.value.id });
		auditCode.value = res.result?.data?.authorizationCode;
		setps.value++;
		return;
	}
	if (setps.value == 3) {
		proTableRef.value.tableData.forEach((item: any) => {
			if (item.id == rowData.value.id) {
				item.xx = auditCode.value;
			}
		});
		codeNumber.value = "";
		from_2.value = {
			password: "",
			identifyCode: ""
		};
		rowData.value = {
			id: "",
			userId: "",
			userName: "",
			userTel: "",
			companyId: "",
			companyName: "",
			authorizationCode: "",
			authorizationSerialNumber: "",
			surplusAuthorization: 2,
			createTime: "",
			updateUserId: "",
			updateUserName: "",
			updateTime: "",
			states: 1
		};
		dialogTableVisible.value = false;
		auditCode.value = "";
		setps.value = 1;
	}
};
// 图形验证码
const data = reactive({
	change_img_code: false, // 刷新验证码
	img_code: "" // 加密后的验证码值
});

// 刷新验证码操作
const changeImageCode = () => {
	data.change_img_code = !data.change_img_code;
};
// 接收组件返回加密后的验证码值
const backImageCode = (code: any) => {
	data.img_code = code;
};
</script>
<style scoped lang="scss">
::v-deep.table-box .table-header .header-button-lf,
.table-main .table-header .header-button-lf {
	float: none !important;
}
.codeFrom {
	height: 200px;
	padding: 50px 0;
	box-sizing: border-box;
	display: flex;
	flex-direction: column;
	justify-content: space-between;
	align-items: center;
}
.steps-button {
	width: 100%;
	display: flex;
	justify-content: center;
}
.from-2 {
	padding: 50px 0;
	box-sizing: border-box;
	.from-item {
		display: flex;
		align-items: center;
		justify-content: flex-start;
		width: 100%;
		margin: 15px auto;
		.label {
			width: 35% !important;
			text-align: right;
		}
		.value {
			flex: 1;
			display: flex;
			align-items: center;
		}
	}
}
</style>
